package org.madmatrix.galarm;

import org.madmatrix.glib.log.ILogger;
import org.madmatrix.glib.log.LoggerFactory;
import org.madmatrix.glib.util.DateUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;

import com.google.gson.Gson;

public class AddingAlarmActivity extends Activity implements View.OnClickListener {

	private static ILogger logger = LoggerFactory.getLogger(AddingAlarmActivity.class);

	/**
	 * 请求码-设置铃声
	 */
	private static final int REQ_CODE_SELECT_RING = 1;

	private Switch swVibrate;
	private Alarm mAlarm;
	private Gson mGson = new Gson();

	private TextView tvTime;
	private TextView tvRepeat;
	private TextView tvMemo;
	private TextView tvAlarmRing;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_alarm);

		getActionBar().setDisplayHomeAsUpEnabled(true);

		String alarmConf = getIntent().getStringExtra("alarm");
		if (!TextUtils.isEmpty(alarmConf)) {
			mAlarm = mGson.fromJson(alarmConf, Alarm.class);
		} else {
			// 如果是新增alarm，则初始化一下alarm
			mAlarm = new Alarm(GAlarmManager.generateAlarmId(this));
			mAlarm.triggerTimeHour = DateUtil.getCurrentHour();
			mAlarm.triggerTimeMinute = DateUtil.getCurrentMinute();
		}

		swVibrate = (Switch) findViewById(R.id.vibrate_switch);
		swVibrate.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				mAlarm.isVibrate = isChecked;
			}
		});
		swVibrate.setChecked(mAlarm.isVibrate);

		findViewById(R.id.item_time).setOnClickListener(this);
		findViewById(R.id.item_repeat).setOnClickListener(this);
		findViewById(R.id.item_ring).setOnClickListener(this);
		findViewById(R.id.item_memo).setOnClickListener(this);
		findViewById(R.id.btn_cancel).setOnClickListener(this);
		findViewById(R.id.btn_ok).setOnClickListener(this);

		tvTime = (TextView) findViewById(R.id.time);
		tvRepeat = (TextView) findViewById(R.id.repeat);
		tvMemo = (TextView) findViewById(R.id.memo);
		tvAlarmRing = (TextView) findViewById(R.id.alarm_ring);

		tvTime.setText(GAlarmManager.getTriggerTime(mAlarm));
		tvRepeat.setText(GAlarmManager.getRepeatDaysDesc(mAlarm));
		tvMemo.setText(mAlarm.memo);
		if (!TextUtils.isEmpty(mAlarm.alarmRingTitle)) {
			tvAlarmRing.setText(mAlarm.alarmRingTitle);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
		default:
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.item_time:
			popupTimePeaker();

			break;
		case R.id.item_repeat:
			popupWeekdayPiker();

			break;
		case R.id.item_ring:
			popupRingSelector();

			break;
		case R.id.item_memo:
			popupMemoEditor();

			break;
		case R.id.btn_cancel:
			setResult(Constants.RETCODE_SUCCESS);
			finish();

			break;
		case R.id.btn_ok:
			Intent intent = new Intent();
			mAlarm.isEnabled = true;
			intent.putExtra("alarm", mGson.toJson(mAlarm));
			setResult(Constants.RETCODE_SUCCESS, intent);

			finish();

			break;
		default:

		}
	}

	/**
	 * 弹出时间设置对话框
	 */
	private void popupTimePeaker() {
		int setHour = Integer.parseInt(String.format("%02d", mAlarm.triggerTimeHour));
		int setMinute = Integer.parseInt(String.format("%02d", mAlarm.triggerTimeMinute));

		TimePickerDialog tpDlg = new TimePickerDialog(this, R.style.GAlarm_Theme_Holo_Dialog, new OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker piker, int hourOfDay, int minute) {
				mAlarm.triggerTimeHour = hourOfDay;
				mAlarm.triggerTimeMinute = minute;

				tvTime.setText(String.format("%02d:%02d", hourOfDay, minute));
			}
		}, setHour, setMinute, true); // 24小时制
		tpDlg.setTitle("时间设置");

		tpDlg.show();
	}

	/**
	 * 弹出重复设置对话框
	 */
	private void popupWeekdayPiker() {
		final boolean[] checkedItems = new boolean[7];
		Weekday[] weekdays = Weekday.values();
		for (int i = 0; i < weekdays.length; ++i) {
			if (mAlarm.weekdays.contains(weekdays[i])) {
				checkedItems[i] = true;
			} else {
				checkedItems[i] = false;
			}
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.GAlarm_Theme_Holo_Dialog);
		builder.setTitle("重复设置");
		builder.setMultiChoiceItems(Weekday.toDescArray(), checkedItems, new OnMultiChoiceClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {

			}
		});

		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mAlarm.weekdays.clear();
				mAlarm.isRepeat = true;
				for (int i = 0; i < checkedItems.length; ++i) {
					if (checkedItems[i]) {
						mAlarm.weekdays.add(Weekday.values()[i]);
					}
				}

				tvRepeat.setText(GAlarmManager.getRepeatDaysDesc(mAlarm));
			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}

	/**
	 * 弹出闹钟铃声选择器
	 */
	private void popupRingSelector() {
		Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM);
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "设置铃声");
		intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
		startActivityForResult(intent, REQ_CODE_SELECT_RING);
	}

	/**
	 * 弹出填写备注的对话框
	 */
	private void popupMemoEditor() {
		final EditText memoEditor = new EditText(this);
		memoEditor.setTextColor(getResources().getColor(android.R.color.white));
		memoEditor.requestFocus();

		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				InputMethodManager inputManager = (InputMethodManager) memoEditor.getContext().getSystemService(
						Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(memoEditor, 0);
			}
		}, 900);

		AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.GAlarm_Theme_Holo_Dialog);
		builder.setTitle("备注");
		builder.setView(memoEditor);
		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String memo = memoEditor.getText().toString();
				if (!TextUtils.isEmpty(memo)) {
					mAlarm.memo = memo;
					tvMemo.setText(mAlarm.memo);
				}
			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (REQ_CODE_SELECT_RING == requestCode) {
			if (null != data) {
				Uri pickedUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
				if (null != pickedUri) {
					logger.d("ring uri picked=" + pickedUri);
					
					// 获取选取的铃声名并设置到界面上
					RingtoneManager ringtoneMgr = new RingtoneManager(this);
					ringtoneMgr.setType(RingtoneManager.TYPE_ALARM); // 需要设置好声音类型，默认取得是TYPE_RINGTONE的列表
					Cursor alarmRingCursor = ringtoneMgr.getCursor();

					for (alarmRingCursor.moveToFirst(); !alarmRingCursor.isAfterLast(); alarmRingCursor.moveToNext()) {
						String uri = alarmRingCursor.getString(RingtoneManager.URI_COLUMN_INDEX) + "/"
								+ alarmRingCursor.getString(RingtoneManager.ID_COLUMN_INDEX);
						if (uri.equals(pickedUri.toString())) {
							String title = alarmRingCursor.getString(RingtoneManager.TITLE_COLUMN_INDEX);
							tvAlarmRing.setText(title);
							mAlarm.alarmRingTitle = title;
							mAlarm.alarmRingUri = pickedUri.toString();
							
							break;
						}
					}
				}
			} else {
				logger.e("failed to set alarm ring, intent is null");
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}
}
